<template>
    <canvas id="watermark" canvas-id="watermark" :style="canvasStyle" ref="canvas"></canvas>
</template>

<script>
    export default {
        props: {
            name: {
                type: String,
                default: ''
            },
            phoneLastDigits: {
                type: String,
                default: ''
            },
            company: {
                type: String,
                default: ''
            }
        },
        data() {
            return {
                canvasId: 'watermarkCanvas',
                watermarkTexts: [],
                canvasStyle: {
                    position: 'absolute',
                    top: '0',
                    left: '0',
                    width: '100vw',
                    height: '100vh',
                    pointerEvents: 'none', // 禁止用户点击
                    zIndex: '1', // 确保水印在最上层
                },
            };
        },
        mounted() {
            this.updateWatermarkTexts();
            this.drawWatermark();
            // 监听窗口大小变化，重新绘制水印
            window.addEventListener('resize', this.drawWatermark);
        },
        beforeDestroy() {
            window.removeEventListener('resize', this.drawWatermark);
        },
        watch: {
            // 监听name和phoneLastDigits的变化
            name: 'updateWatermarkTexts',
            phoneLastDigits: 'updateWatermarkTexts',
        },
        methods: {
            updateWatermarkTexts() {
                this.watermarkTexts = [
                    `${this.company}`,
                    `${this.name} ${this.phoneLastDigits}`,
                    `${this.getFormattedDate()}`,
                ];
                this.drawWatermark();
            },
            drawWatermark() {
                const query = uni.createSelectorQuery().in(this);
                // 使用exec获取画布的真实宽高
                query.select('#watermark').fields({ node: true, size: true }).exec((res) => {
                    if (!res || res.length === 0) {
                        console.error('Failed to get canvas context');
                        return;
                    }
                    // 获取canvas宽高
                    const { width, height } = res[0];

                    const ctx = uni.createCanvasContext('watermark', this);

                    // 清空画布
                    ctx.clearRect(0, 0, width, height);

                    // 水印样式设置
                    ctx.setFontSize(14);
                    ctx.setFillStyle('rgba(169, 169, 169, 0.4)'); // 灰色带透明度
                    ctx.rotate(-Math.PI / 6); // 逆时针旋转30度

                    // 计算文本重复次数
                    const textWidths = this.watermarkTexts.map((text) =>
                        ctx.measureText(text).width
                    );
                    const maxTextWidth = Math.max(...textWidths);
                    const lineHeight = 30; // 行间距
                    const gap = 100; // 水印间距

                    // 填充水印
                    for (let x = -width; x < width * 2; x += maxTextWidth + gap) {
                        for (let y = -height; y < height * 2; y += lineHeight * this.watermarkTexts.length + gap) {
                            // 分行显示文本
                            this.watermarkTexts.forEach((text, index) => {
                                ctx.fillText(text, x, y + index * lineHeight);
                            });
                        }
                    }

                    // 重置旋转角度
                    ctx.rotate(Math.PI / 6); // 恢复旋转的角度

                    // 最后需要调用draw方法将内容绘制到画布上
                    ctx.draw();
                })
            },
            getFormattedDate() {
                const date = new Date();
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            },
        },
    };
</script>

<style scoped>
    canvas {
        display: block;
    }
</style>